package cmd

import (
	"fmt"
	"init-homework/utils"
	"io/fs"
	"os"
	"strings"

	"github.com/spf13/cobra"
)

var homeworkPath string

func findFileNameById(filename, id string, matchFn func(filename string) bool) string {
  var dirList []fs.FileInfo = utils.FlatDir(filename)
  var matchedName string
  for _, dir := range dirList {
    if matchFn(dir.Name()) {
      matchedName = dir.Name()
      break
    }
  }
  if matchedName == "" {
    fmt.Println("没有匹配到学号")
  }
  fields := strings.Split(matchedName, "-")
  return fields[len(fields)-1]
}

// 在homework/第x周/ 下面, 生成目录 GO-7期-id-name
func genDir(id, name string) {
  weeksDirInfo := utils.LsDir(homeworkPath)
  for _, weeksDirInfo := range weeksDirInfo {
    fullPath := homeworkPath + weeksDirInfo.Name()
    homeworks := utils.LsDir(fullPath)
    isExist := false
    for _, workInfo := range homeworks {
      if strings.Contains(workInfo.Name(), id) {
        isExist = true
        break
      }
    }
    if !isExist {
      fullDirPath := fullPath + "/GO-7期-" + id + "-" + name
      os.Mkdir(fullDirPath, 0777)
      fullFilePath := fullDirPath + "/main.go"
      os.WriteFile(fullFilePath, []byte("package main\n\nfunc main() {\n\n}"), 0777)
      fmt.Println("已生成: ", fullFilePath)
    }
  }
}

func run(id string) {
  name := findFileNameById(homeworkPath, id, func(filename string) bool {
    return strings.Contains(filename, id)
  })
  if name == "" {
    fmt.Println("未匹配到历史作业, 找不到名字.")
    name = utils.Prompt("请输入姓名: \n")
  }
  fmt.Println("name:", name)
  genDir(id, name)
}

func checkProject() {
  exists := utils.IsExist(homeworkPath)
  if !exists {
    fmt.Println("请在项目根目录下执行, 当前目录未检测到homework目录")
    os.Exit(1)
  }
}

var rootCmd = &cobra.Command{
  Use:   "gd",
  Short: "gd就是generate-dir, 生成本周homework的目录",
  Long: `gd就是generate-dir, 生成本周homework的目录, 项目地址: todo`,
  Run: func(cmd *cobra.Command, args []string) {
    // Do Stuff Here
    checkProject()
    if id == "" {
      fmt.Println("请输入学号")
      fmt.Println("\t例: gd -i 7099")
      os.Exit(1)
    } else{
      fmt.Println("学号:", id)
      run(id)
    }
  },
}

var id string
func init(){
  str, _ := utils.ExecPath()
  fmt.Println("pwd: ", str)
  homeworkPath = str + "/homework/"
  rootCmd.Flags().StringVarP(&id, "id", "i", "", "学号")
}

func Execute() {
  if err := rootCmd.Execute(); err != nil {
    fmt.Fprintln(os.Stderr, err)
    os.Exit(1)
  }
}